package client;

import common.LogUtil;
import common.ServiceMapping;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Logger;

/**
 * 本地服务管理
 */
public class ServiceManager {
    private static final Logger logger = LogUtil.getLogger(ServiceManager.class.getName());

    // 关联的客户端
    private final TunnelClient client;

    // 服务映射
    private final Map<String, LocalService> services = new ConcurrentHashMap<>();

    // 连接映射
    private final Map<Integer, ServiceConnection> connections = new ConcurrentHashMap<>();

    /**
     * 构造函数
     */
    public ServiceManager(TunnelClient client) {
        this.client = client;
    }

    /**
     * 添加服务
     */
    public void addService(ServiceMapping mapping) throws IOException {
        String name = mapping.getName();
        if (services.containsKey(name)) {
            logger.warning("Service already exists: " + name);
            return;
        }

        // 创建本地服务
        LocalService service = new LocalService(this, mapping);
        services.put(name, service);

        logger.info("Service added: " + name);
    }

    /**
     * 移除服务
     */
    public void removeService(String name) {
        LocalService service = services.remove(name);
        if (service != null) {
            logger.info("Service removed: " + name);
        }
    }

    /**
     * 获取服务
     */
    public LocalService getService(String name) {
        return services.get(name);
    }

    /**
     * 创建连接
     */
    public void createConnection(int connectionId) throws IOException {
        // 简单实现：使用第一个服务
        if (services.isEmpty()) {
            logger.warning("No service available for connection: " + connectionId);
            return;
        }

        LocalService service = services.values().iterator().next();

        // 创建服务连接
        ServiceConnection connection = new ServiceConnection(this, service, connectionId);
        connections.put(connectionId, connection);

        // 启动连接
        connection.start();

        logger.info("Connection created: " + connectionId + " for service: " + service.getConfig().getName());
    }

    /**
     * 关闭连接
     */
    public void closeConnection(int connectionId) {
        ServiceConnection connection = connections.remove(connectionId);
        if (connection != null) {
            connection.close();
            logger.info("Connection closed: " + connectionId);
        }
    }

    /**
     * 转发数据到本地服务
     */
    public void forwardToLocalService(int connectionId, byte[] data) throws IOException {
        ServiceConnection connection = connections.get(connectionId);
        if (connection != null) {
            connection.writeToLocalService(data);
        } else {
            logger.warning("Connection not found for forwarding: " + connectionId);
        }
    }

    /**
     * 关闭所有连接
     */
    public void closeAllConnections() {
        for (ServiceConnection connection : connections.values()) {
            connection.close();
        }
        connections.clear();
    }

    /**
     * 关闭所有服务
     */
    public void closeAllServices() {
        // 首先关闭所有连接
        closeAllConnections();

        // 然后清除服务
        services.clear();
    }

    /**
     * 获取客户端
     */
    public TunnelClient getClient() {
        return client;
    }
}
